/*
 * Created on Jan 6, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package bmoofxbridge;

import il.co.fibi.bmo.BMOLib.BMO;
import il.co.fibi.bmo.BMOLib._DBMO;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;

import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import net.ofx.types.x2003.x04.OFXDocument;

import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlOptions;
import org.mortbay.http.HttpContext;
import org.mortbay.http.HttpServer;
import org.mortbay.http.handler.ResourceHandler;
import org.mortbay.jetty.servlet.ServletHandler;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import bmoofxbridge.model.Model;

import com.develop.jawin.COMException;

/**
 * @author Cyril
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class BMODemo extends Frame {
	static BMODemo demo = null;
	static private _DBMO BMOcx;

	BMOComponent component = null;

	
	public static void main(String[] args) throws COMException {
		demo = new BMODemo();
		demo.show();
//		BMOcx = demo.component.control;
		
		DataProcessor processor = new DataProcessor(demo.component.control);
		System.out.println("Please, Login!");
		processor.loginToBMO();
		System.out.println("Extracting Data");
		processor.extractData();
		System.out.println("Preparing Report");
		Document report = processor.getReport(null);
		System.out.println("Saving Report");
		processor.saveReport(report, "D:\\Work\\test2.ofx");
		System.out.println("Done!");
		
		try{
		ReportServlet.processor = processor;	
		HttpServer server = new HttpServer();
		server.addListener(":8080");
		HttpContext OFXcontext = server.getContext("/");
		ServletHandler handler= new ServletHandler();
		handler.addServlet("Report","/report/OFX",
		                   "bmoofxbridge.ReportServlet");
		OFXcontext.addHandler(handler);
		
		HttpContext brandingContext = server.getContext("/branding");
		brandingContext.setResourceBase("./");
		brandingContext.addHandler(new ResourceHandler());
		
		
		
		
		server.start();
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		
		//System.exit(0);

//		BMOParser parser = new BMOParser(BMOcx);
//		Model model = new Model();
//		parser.fillModel(model);
//		OFXDocument doc = parser.getFullStatement(model);
		//XmlCursor curs = doc.newCursor();
		//curs.toNextToken();
		//curs.insertProcInst(
		//				"OFX",
		//				"OFXHEADER=\"200\" VERSION=\"200\" SECURITY=\"NONE\" OLDFILEUID=\"NONE\" NEWFILEUID=\"NONE\"");
		//XmlOptions opts = new XmlOptions();
		//opts.setSavePrettyPrint();
		//opts.setSavePrettyPrintIndent(0);
		
//		Document docDomNode = (Document) doc.newDomNode();
//		Element ofxDomElement = docDomNode.getDocumentElement();
//		ofxDomElement.setPrefix(null);
//		ofxDomElement.removeAttribute("xmlns");
//		ofxDomElement.removeAttribute("xmlns:ns");
//
//		Document newDoc = docDomNode.getImplementation().createDocument(null,
//				"OFX", null);
//		org.w3c.dom.ProcessingInstruction pi = newDoc
//				.createProcessingInstruction(
//						"OFX",
//						"OFXHEADER=\"200\" VERSION=\"200\" SECURITY=\"NONE\" OLDFILEUID=\"NONE\" NEWFILEUID=\"NONE\"?");
//		newDoc.insertBefore(pi, newDoc.getDocumentElement());
//		Element newOfxDomElement = newDoc.getDocumentElement();
//		NodeList children = ofxDomElement.getChildNodes();
//
//		for (int i = 0; i < children.getLength(); i++) {
//			Node node = children.item(i);
//			newOfxDomElement.appendChild(newDoc.importNode(node, true));
//		}
//
//		try {
//			OutputStream os = new FileOutputStream("D:\\Work\\test2.ofx");
//			PrintStream ps = new PrintStream(os);
//			printDocument(newDoc, ps);
//			System.out.println("done!");
//
//		} catch (TransformerFactoryConfigurationError e1) {
//			// TODO Auto-generated catch block
//			e1.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}

		

	}

	/**
	 * @param ocx
	 * @throws COMException
	 */
	private static Object[] print(_DBMO BMOcx) {
		short[] indexes = { 0, 4, 1, 4, 2, 6, -1, 4 };

		int valCount = 0;
		for (int i = 1; i < indexes.length; i += 2) {
			valCount += indexes[i];
		}
		Object[] values = new Object[valCount];
		int valIndx = 0;

		for (int i = 0; i < indexes.length; i += 2) {
			short ind1 = indexes[i];
			short cnt = indexes[i + 1];
			for (short ind2 = 0; ind2 < cnt; ind2++) {
				Object val = null;
				try {
					if (ind1 >= 0) {
						val = BMOcx.ValueC(ind1, ind2);
					} else {
						val = new Double(BMOcx.ValueCD(ind2));
					}
				} catch (COMException e) {
				}
				values[valIndx++] = val;
				System.out.print(val);
				System.out.print(" , ");
			}
		}
		System.out.println();
		return values;
	}

	/**
	 * This is the default constructor
	 */
	public BMODemo() throws COMException {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() throws COMException {
		this.setSize(500, 500);
		this.setVisible(true);
		this.setTitle("MultiBank OFX Bridge");
		this.setName("MultiBank OFX Bridge");
		component = new BMOComponent(BMO.progID);
		this.add(component, BorderLayout.SOUTH);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent evt) {
				System.exit(0);
			}
		});
	}

	public static final String XML_PRINT_TRANSFORMER = "<?xml version=\"1.0\"?>"
			+ "<xsl:stylesheet "
			+ "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\" "
			+ "xmlns:xalan=\"http://xml.apache.org/xslt\" "
			+ "exclude-result-prefixes=\"#default,xmlns,ns\" "
			+ ">"
			+ "<xsl:output method=\"html\" indent=\"yes\" xalan:indent-amount=\"3\"/>"
			+ "<xsl:strip-space elements=\"*\" />"
			+ "<xsl:template match=\"/\">"
			+ "<xsl:text disable-output-escaping=\"yes\">&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?&gt;\n</xsl:text>"
			+ "<xsl:apply-templates/>"
			+ "</xsl:template>"
			+ "<xsl:template match=\"@*|comment()|processing-instruction()|text()|*\">"
			+ " <xsl:copy>"
			+ " <xsl:apply-templates select=\"@*|comment()|processing-instruction()|text()|*\"/>"
			+ " </xsl:copy>" + "</xsl:template>" + "</xsl:stylesheet>";

	/**
	 * Serialize a Document to a PrintStream
	 *
	 * @param aDocument The document to save
	 * @param aOut The output stream
	 */
	static void printDocument(Document aDocument, PrintStream aOut) {
		try {
			TransformerFactory tfactory = TransformerFactory.newInstance();
			Element tempElement = aDocument.getDocumentElement();
			StringReader xslReader = new StringReader(XML_PRINT_TRANSFORMER);
			Templates template = tfactory.newTemplates(new StreamSource(
					xslReader));
			Transformer serializer = template.newTransformer();
			serializer.transform(new DOMSource(aDocument), new StreamResult(
					aOut));
		} catch (Exception e) {
			System.err.println("Exception from XML serializing: "
					+ e.toString());
			e.printStackTrace(System.err);
		}
	}
	
	private void playGround(){
		//		BMOcx.Close();
		//		BMOcx.Command("open visanew.dat");
		//		BMOcx.Command("Set Field Date 1");
		//		BMOcx.Command("Set Op *");
		//		BMOcx.Command("Set Val 00/00/00");
		//		BMOcx.Command("Set Sort Ascend");
		//		BMOcx.Command("Build");
		//		BMOcx.SetHead();
		//		BMOcx.SavePos((short)0);
		
		/*		
		 BMOcx.Close();
		 BMOcx.Command("open visaold.dat");
		 BMOcx.Command("Set Field String 2");
		 BMOcx.Command("Set Op *");
		 BMOcx.Command("Set Val *");
		 BMOcx.Command("Set Sort Ascend");
		 BMOcx.Command("Build");
		 BMOcx.Sort((short)2,(short)3,1);
		 BMOcx.SetHead();
		 BMOcx.SavePos((short)0);
		 
		 ArrayList rows = new ArrayList();
		 ArrayList crdtrans = new ArrayList();
		 
		 while (!BMOcx.IsEndOfList()) {			
		 BMOcx.Move(1);
		 rows.add(print(BMOcx));
		 crdtrans.add(new CreditCardTransaction(parser));
		 }
		 */
		//		BMOcx.Close();
		//		BMOcx.Command("open tnuot.dat");
		//		//BMOcx.Command("set field string 2");
		//		//BMOcx.Command("set op #");
		//		//BMOcx.Command("set val *"+item+"*");
		//		BMOcx.Command("build");
		//		BMOcx.SetHead();
		//		BMOcx.SavePos((short)0);
		
//		Node domDocNode = doc.newDomNode();
		//Document docDoc = (Document) domDocNode;
		//ProcessingInstruction

		//    	Account[] accounts = parser.getBankAccounts();
		//    	try {
		//    	    //BMOParser.save(accounts,System.out);
		//		} catch (IOException e) {
		//			// TODO Auto-generated catch block
		//			e.printStackTrace();
		//		}
		//		StatementTransaction[] transactions = parser.getCheckingTransactions();
		//    	try {
		//    	    BMOParser.save(transactions,System.out);
		//		} catch (IOException e) {
		//			// TODO Auto-generated catch block
		//			e.printStackTrace();
		//		}
	}

}